package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

	"github.com/xuperchain/xuper-sdk-go/v2/account"
	"github.com/xuperchain/xuper-sdk-go/v2/xuper"
)

// var (
//
//	node   = "39.156.69.83:37100"
//	bcname = "xuper"
//
// )
type Record struct {
	GoodsID      string `json:"goodsId"`
	UpdateRecord string `json:"updateRecord"`
	Reason       string `json:"reason"`
	Place        string `json:"place"`
	Name         string `json:"name"`
	EnvT         string `json:"envT"`
	EnvH         string `json:"envH"`
	Fac          string `json:"fac"`
	Person       string `json:"person"`
	Time         string `json:"time"`
	Result       string `json:"result"`
}

type Product struct {
	GoodsID      string `json:"goodsId"`
	UpdateRecord string `json:"updateRecord"`
	Reason       string `json:"reason"`
	Place        string `json:"place"`
	Name         string `json:"name"`
	EnvT         string `json:"envT"`
	EnvH         string `json:"envH"`
	Fac          string `json:"fac"`
	Person       string `json:"person"`
	Time         string `json:"time"`
	Result       string `json:"result"`
}

func clientConfigExample() {
	// 39.156.69.83:37100 为开放网络节点地址。
	// xuper.WithConfigFile("yourSDK.yaml") 设置使用的配置文件。
	xclient, err := xuper.New("39.156.69.83:37100", xuper.WithConfigFile("your config file address"))
	if err != nil {
		fmt.Println(err)
		return
	}

	status, err := xclient.QuerySystemStatus()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(status)
}

// 连接用户账户
func getAccount() (*account.Account, error) {
	acc, err := account.GetAccountFromFile("your private key", "xxxxxx")
	if err != nil {
		fmt.Printf("GetAccountFromFile err: %v\n", err)
		return nil, err
	}
	fmt.Printf("address=%s\n", acc.Address)

	return acc, nil
}

func invokeContractWithId(id string) (*xuper.Transaction, error) {
	// 连接用户账户
	acc, err := getAccount()
	if err != nil {
		return nil, err
	}
	// 调用合约
	client, err := xuper.New("39.156.69.83:37100")
	if err != nil {
		return nil, err
	}

	contractAccount := "XC5927549071230459@xuper"
	err = acc.SetContractAccount(contractAccount)
	if err != nil {
		return nil, err
	}

	contractName := "your contract name"
	contractMethod := "your method"

	// 合约方法参数
	args := map[string]string{
		"id": id,
	}

	//invoke
	tx, err := client.InvokeWasmContract(acc, contractName, contractMethod, args)
	if err != nil {
		return nil, err
	}

	return tx, nil
}

func httpTest2() {
	http.HandleFunc("/sendjson", func(w http.ResponseWriter, r *http.Request) {
		// 设置响应头
		w.Header().Set("Content-Type", "application/json")

		// 设置允许的请求来源
		w.Header().Set("Access-Control-Allow-Origin", "*")
		// 设置允许的请求方法
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		// 设置允许的请求头部
		w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type")
		records := []Record{}
		id := r.URL.Query().Get("id")
		// 调用合约方法，并将ID作为参数传递
		result, err := invokeContractWithId(id)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		lines := strings.Split(string(result.ContractResponse.Body), "\n") //根据换行符将数据拆分为行
		for _, line := range lines {
			line = strings.TrimSpace(line) //除去空格
			if line == "" {
				continue
			}

			recordFields := strings.Split(line, ",") //使用逗号将每行数据拆分为字段和值
			record := Record{}
			for _, field := range recordFields {
				parts := strings.SplitN(field, "=", 2) //使用等号将字段和值拆分
				key := strings.TrimSpace(parts[0])
				value := strings.TrimSpace(parts[1])
				switch key {
				case "goodsId":
					record.GoodsID = value
				case "updateRecord":
					record.UpdateRecord = value
				case "reason":
					record.Reason = value
				case "place":
					record.Place = value
				case "name":
					record.Name = value
				case "envT":
					record.EnvT = value
				case "envH":
					record.EnvH = value
				case "fac":
					record.Fac = value
				case "person":
					record.Person = value
				case "time":
					record.Time = value
				case "result":
					record.Result = value
				}
			}
			records = append(records, record)
		}

		// 编码为 JSON 字节数组
		jsonData, err := json.Marshal(records)
		if err != nil {
			fmt.Println("JSON encoding error:", err)
			return
		}

		fmt.Println(string(jsonData))

		w.Write([]byte(jsonData))
	})

	http.ListenAndServe(":3000", nil)

}

func main() {
	clientConfigExample()
	httpTest2()
}
